package com.gscitysfy.cus.drain.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

public class FileUtil {

    private FileUtil() {}

    public static String download(String url, String dir) throws Exception {
        File f = new File(dir);
        if (!f.exists()) {
            f.mkdirs();
        }
        int endIndex = url.lastIndexOf("?");
        String imgName = url.substring(url.lastIndexOf("/") + 1, endIndex == -1 ? url.length() : endIndex);
        InputStream in = null;
        String savePath = f.getAbsolutePath() + File.separator + imgName;
        FileOutputStream fo = null;
        try {
            in = new URL(url).openStream();
            File saveFile = new File(savePath);
            if(saveFile.exists()){
                return savePath;
            }
            fo = new FileOutputStream(saveFile);
            byte[] buf = new byte[1024];
            int length = 0;
            while ((length = in.read(buf, 0, buf.length)) != -1) {
                fo.write(buf, 0, length);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException("文件未找到");
        } finally {
            if (null != in) {
                in.close();
            }
            if (null != fo) {
                fo.close();
            }
        }
        return savePath;
    }
}